package hn.cch.version.lts11.http;

import org.junit.jupiter.api.Test;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Paths;
import java.time.Duration;

public class HttpClientTest {


    @Test
    public void testCustomHttpClient() throws FileNotFoundException {

        HttpClient httpClient = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_1_1)
            .followRedirects(HttpClient.Redirect.NORMAL)
            .connectTimeout(Duration.ofSeconds(20))
            // .proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 8080)))
            .authenticator(Authenticator.getDefault())
            .build();


        HttpRequest httpRequest = HttpRequest.newBuilder()
            .uri(URI.create("http://www.baidu.com"))
            .timeout(Duration.ofSeconds(20))
            .header("Content-type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofFile(Paths.get("data.json")))
            .build();
    }

    @Test
    public void testSimpleHttpClient() throws IOException, InterruptedException {
        HttpClient httpClient = HttpClient.newHttpClient();

        HttpRequest httpRequest = HttpRequest.newBuilder(URI.create("http://localhost:8080/text1")).build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        if (statusCode == 200) {
            System.out.println(httpResponse.body());
        }
    }


}
